# -*- coding: utf-8 -*-
import logging
from Url import Url
import Setting
from ConfigReader import config_reader
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
from sqlalchemy.orm import sessionmaker


class DbAccess(object):
    def __init__(self, pool_size=0):
        db_url = Setting.SQL_ENGINE_URL_FORMAT.format(
            dialect=config_reader.get('Main', 'DB_DIALECT'),
            driver=config_reader.get('Main', 'DB_DRIVER'),
            user=config_reader.get('Main', 'DB_ACCOUNT'),
            password=config_reader.get('Main', 'DB_PASSWORD'),
            host=config_reader.get('Main', 'DB_HOST'),
            dbname=config_reader.get('Main', 'DB_DBNAME'))

        if pool_size == 0:
            self.engine = create_engine(
                db_url, poolclass=NullPool, connect_args={'read_timeout': 60})
        else:
            self.engine = create_engine(
                db_url,
                pool_size=pool_size,
                pool_recycle=Setting.SQL_ENGINE_POOL_RECYCLE,
                connect_args={'read_timeout': 60}
            )
        self.session = sessionmaker(bind=self.engine)

    def add_url_mapping(self, long_url, short_url):
        url = Url(long_url=long_url, short_url=short_url)
        self.session.add(url)
        self.session.commit()

    def get_long_url(self, short_url):
        records = self.session.query(Url).filter_by(short_url=short_url).All()
        if len(records) == 0:
            return None
        elif len(records) == 1:
            return records[0]
        elif len(records) > 1:
            raise Exception(
                "Multiple records found for short url: %s", short_url)

    def get_short_url(self, long_url):
        records = self.session.query(Url).filter_by(long_url=long_url).All()
        if len(records) == 0:
            return None
        elif len(records) == 1:
            return records[0]
        elif len(records) > 1:
            raise Exception("Multiple records found for long url: %s", long_url)
